<?php
require_once 'widgets/TSkinnableWidget.inc';

/**
 * 
 * @author kras
 * @property TCMSCategoryModel $CategoryModel
 */

class TToCWidget extends TSkinnableWidget {
	protected $_int_length_ = 6;
	protected $_conf_category_ = null;

/**
 * @var TCMSCategoryModel
 */	
	protected $_ioc_category_model_;

/**
 * @var IKeyValueRepository
 */	
	protected $_ioc_settings_repo_;
	
	protected function checkSource($src){
		return $src instanceof TCMSPageModel;
	}
	
	
	public function Categories(){
		$c = $this->Category;
		if (!$c)
			if ($this->SettingsRepo)
			$c = $this->SettingsRepo->GetValue("ToCRoot");

		if ($c){
			$cat = $this->CategoryModel->GetList(new TListOptions(array(new TFilterOption("Slug", TConditionType::C_EQUAL, $c))));
			$sc = null;
			foreach ($cat as $c1){				
				$sc = $this->CategoryModel->GetContents($c1->ItemId(),true,new TListOptions(array(new TFilterOption('IsPublished', TConditionType::C_EQUAL, true))));
				break;
			}
			if (($sc instanceof IIterator) || is_array($sc))
				return $sc;
		}
		return new TArrayIterator(array());
	}
	
	public function CategoryPages(IItem $category){
		return $this->Source->GetList(new TListOptions(array(new TFilterOption('Categories', TConditionType::C_IN, array($category->ItemId())),new TFilterOption('IsPublished', TConditionType::C_EQUAL, true)),array(new TSortingOption("Published",TSortingType::SORT_DESC)),$this->Length));
	}
	
	public function defaultOutput(IThemeEngine $engine){
		$categories = $this->Categories();
		?>
		<div id="<?php echo $this->Name(); ?>" class="toc">
		<?php
		foreach ($categories as $s){
		?>
			<div class="toc-column">
			<a class="heading" href="<?php echo htmlentities($this->Response()->Service()->ItemNavigationUrl($s)); ?>"><?php echo $s->Name; ?></a>
			<?php
			$pages = $this->CategoryPages($s);
			foreach ($pages as $p){
				?>
				<a href="<?php echo htmlentities($this->Response()->Service()->ItemNavigationUrl($p)); ?>"><?php echo $p->Title; ?></a>
				<?php
			}
			?>
			</div>
		<?php
		}
		?>
		</div>
		<?php 
	}
}